package file;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class Archivo {
	//ATRIBUTOS
	private File ruta = null;
	private ObjectOutputStream escritor;
	private ObjectInputStream lector;
	
	//CONSTRUCTOR
	public Archivo(String r){
		ruta = new File(r);
	}
	
	
	//METODOS
	public void limpiarArchivo(){
	   ruta.delete();
	}
	
	public void AgregarRegistro(Object registro) throws FileNotFoundException, IOException{
	      if(ruta.exists())
	      {
	          escritor = new AppendableObjectOutputStream(new FileOutputStream(ruta, true));  
	          escritor.writeUnshared(registro);
	          escritor.close();  
	      
	       }
	      else {
	    	  escritor = new ObjectOutputStream(new FileOutputStream(ruta, true));        
	          escritor.writeUnshared(registro);
	          escritor.close();            
	       }
	}
	
	
	
	
	public List<Object> ConsultarRegistros() throws FileNotFoundException, IOException, ClassNotFoundException{
		Object registro = null;
		List<Object> lista = new ArrayList<Object>();
		
		try
		{
			if(lector == null)
			lector = new ObjectInputStream(new FileInputStream(ruta));
			while(true)
			{
				registro = lector.readObject();
				lista.add(registro);
			}

		}
		catch(EOFException ex)
		{
			
		}
		return lista;
	}

	
	public String ListaRegistros() throws FileNotFoundException, IOException, ClassNotFoundException{
		
		String lista = "<html>";
		
		Object registro = null;
		
		try
		{
			if(lector == null)
			lector = new ObjectInputStream(new FileInputStream(ruta));
			while(true)
			{
				registro = lector.readObject();
				lista +=  registro + "<br>";
			}
		}
		catch(EOFException ex)
		{
			lista += "</html>";
		}
		
		return lista;
	}
	
}